<template>
  <div>

    <div style="margin: 10px 0">
      <el-input style="width: 200px; height: 30px; margin-right: 10px;" suffix-icon="Search" placeholder="请输入用户名" v-model="username"></el-input>
      <el-button class="ml-5" type="primary" @click="load" style="height: 25px;">搜索</el-button>
      <el-button type="warning" @click="reset" style="height:25px">重置</el-button>
    </div>
    <div style="margin: 15px 0">
      <el-button class="ml-5" type="primary" @click="handleAdd" style="height: 25px;">新增 <el-icon style="margin-left: 5px"><CirclePlus /></el-icon></el-button>
      
      <el-popconfirm
          class="ml-5"
          confirm-button-text='确定'
          cancel-button-text='取消'
          icon="InfoFilled"
          icon-color="red"
          title="您确定批量删除这些数据吗？"
          @confirm="delBatch"
          width=180
      >
      <template #reference>
        <el-button style="height: 25px" class="ml-5" type="danger">批量删除 <el-icon style="margin-left: 5px;"><Remove /></el-icon></el-button>
      </template>
      </el-popconfirm>
    </div>


    <el-table :data="tableData" border stripe header-cell-class-name="headerBg" :cell-style="{textAlign: 'center'}" 
    @selection-change="handleSelectionChange" :header-cell-style="{'text-align': 'center'}">
      <el-table-column type="selection" width="55"></el-table-column>
      <el-table-column prop="id" label="ID" width="80"></el-table-column>
      <el-table-column prop="nickName" label="用户名" width="140"></el-table-column>
      <el-table-column prop="sex" label="性别" width="120"></el-table-column>
      <el-table-column prop="age" label="年龄"></el-table-column>
      <el-table-column prop="address" label="地址" width="200"></el-table-column>
      <el-table-column prop="points" label="积分"></el-table-column>
      <el-table-column prop="sumPoints" label="总积分"></el-table-column>
      <el-table-column prop="phone" label="电话"></el-table-column>
      <el-table-column prop="isCarbon" label="是否是碳行者"></el-table-column>
      <el-table-column label="操作" width="200">
        <template #default="scope">
          <el-button type="success" style="height: 25px;" @click="handleEdit(scope.row)">编辑<el-icon style="margin-left: 5px;"><Edit /></el-icon></el-button>

          <el-popconfirm
              confirm-button-text='确定'
              cancel-button-text='取消'
              icon="InfoFilled"
              icon-color="red"
              title="您确定删除吗？"
              @confirm="del(scope.row.id)"
          >
          <template #reference>
            <el-button type="danger" style="height: 25px">删除<el-icon style="margin-left: 5px;"><DeleteFilled /></el-icon></el-button>
          </template>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>
    <div style="margin: 20px 10px;">
      <el-pagination
      v-model:current-page="pageNum"
      v-model:page-size="pageSize"
      :page-sizes="[3, 5, 8]"
      :disabled="false"
      :background="true"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    />
    </div>

    <el-dialog title="用户信息" v-model="dialogFormVisible" width="30%">
      <el-form label-width="100px" size="default">
        <el-form-item label="用户名">
          <el-input v-model="form.nickName" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="性别">
          <el-input v-model="form.sex" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="年龄">
          <el-input v-model="form.age" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="地址">
          <el-input v-model="form.address" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="积分">
          <el-input v-model="form.points" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="总积分">
          <el-input v-model="form.sumPoints" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="电话">
          <el-input v-model="form.phone" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="碳行者">
          <el-input v-model="form.isCarbon" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
      <div class="dialog-footer">
        <el-button style="height: 30px;" @click="dialogFormVisible = false">取消</el-button>
        <el-button style="height: 30px" type="primary" @click=save>确认</el-button>
      </div>
    </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">

import instance from '@/utils/request';
import { ElMessage } from 'element-plus';
import {ref, onMounted, reactive} from 'vue'
import { toRaw } from 'vue';
  const tableData = ref([])
  const pageNum = ref(1)
  const pageSize = ref(5)
  const total = ref(100)
  const form = ref({
    id: '',
    nickName: '',
    sex: '',
    age: '',
    address: '',
    points: '',
    sumPoints: '',
    phone: '',
    isCarbon: ''
  })
  const username = ref('')
  const selectedItems = ref([])
  const dialogFormVisible = ref(false)

  onMounted(() => {
    load()
  })

  const load = async () => {
    await instance.get('/admin/page', {
      params: {
        pageNum: pageNum.value,
        pageSize: pageSize.value,
        username: username.value
      }
    }).then(res => {
      tableData.value = res.data.data.records
      tableData.value.map(item => {
        item.isCarbon = item.isCarbon ? '是' : '否'
      })
      total.value = res.data.data.total
    })
  }

  const handleSelectionChange = (row: any) => {
    selectedItems.value = JSON.parse(JSON.stringify(row))
  }

  const handleCurrentChange = (value: number) => {
    pageNum.value = value
    load()
  }
  
  const handleSizeChange = (value: number) => {
    pageSize.value = value
    load()
  }

  const delSuccess = () => {
    ElMessage({
      message: '删除成功',
      type: 'success',
    })
}
  const updateSuccess = () => {
    ElMessage({
      message: '更新成功',
      type: 'success'
    })
  }

  const updataFail = () => {
    ElMessage({
      message: '更新失败',
      type: 'error'
    })
  }

const delBatchSuccess = () => {
  ElMessage({
      message: '批量删除成功',
      type: 'success',
    })
}

 const delFail = () => {
    ElMessage({
      message: '删除失败',
      type: 'error'
    })
  }

  const handleEdit = (row: any) => {
    dialogFormVisible.value = true
    form.value = row
    load()
  }
  const del = async (value: number) => {
    await instance.get('/admin/deleteOneUser', {
      params: {
        id: value
      }
    }).then(res => {
      console.log(res)
      if(res.data.code == '200'){
          load()
          delSuccess()
      }else{
        delFail()
      }

    })
  }

  const delBatch = async () => {
   const ids = selectedItems.value.map(item => item.id)
   await instance.post('/admin/deleteSelectUser', ids).then(res => {
    if(res.data.code == '200'){
      load()
      delBatchSuccess()
    }else{
      ElMessage({
        message: '批量删除失败',
        type: 'error'
      })
    }
   })
  }

  const reset = () => {
    username.value = ''
    load()
  }

  const save = () => {
     const formObj = toRaw(form.value)
     formObj.isCarbon = formObj.isCarbon == '是' ? true : false
     console.log(formObj)
         instance.post('/admin/updateOrInsertUser', formObj).then(res => {
         if(res.data.code == '200'){
          load()
          updateSuccess()
         }else{
          load()
          updataFail()
         }
      })
      dialogFormVisible.value = false
  }

  const handleAdd = async () => {
      dialogFormVisible.value = true
      form.value = {}
  }

</script>


<style scoped>
.headerBg{
  background-color: #eee !important;
}
</style>